<?php
/* ******************************
 * Overhead Out aJax actions
 * ******************************
 */
 
include('../../includes/classes/core.php');
$action = $_REQUEST['act'];
$error	= '';
$data	= '';
switch ($action) {
    case 'get_add_page':
		$page		= GetPage('');
		$data		= array('page' => $page);
		
        break;
    case 'get_edit_page':
	    $act_id		= $_REQUEST['id'];
		$page		= GetPage(GetBuyingAct($act_id));
        
        $data 		= array('page'	=> $page);
        
        break;
    case 'get_list':
	    $count	 = $_REQUEST['count'];
	    $hidden	 = $_REQUEST['hidden'];
	    $rResult = mysql_query("SELECT `O`.`id` AS `id`,
									   `O`.`waybill_number`,
									   IFNULL(CONCAT('(',`O`.`seller_tin`,') ', `O`.`seller_name`),'()') AS `partner`,
									   `O`.`full_amount`,
									   DATE(`O`.`activate_date`)
								FROM `overhead` AS `O` LEFT JOIN `overhead_types` AS `OT`
									ON `O`.`type` = `OT`.`id`
								WHERE `O`.`stream` = 2");
		$data = array(
			"aaData"	=> array()
		);
		
		if(!$rResult){
		    $error = 'Invalid query: ' . mysql_error();
		}else{
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
				}
				$data['aaData'][] = $row;
			}		
		}
		
        break;
    case 'save_buying_act':
		$act_id 	= $_REQUEST['id'];

		$arr = array(
				//Object ID
				"status"			=> $_REQUEST['stat'],
				"o_obj"				=> $_REQUEST['obj'],
				"lid"				=> $_REQUEST['lid'],
				
				"d_number"			=> $_REQUEST['dn'],
				"activate_date"		=> $_REQUEST['ad'],
				
				//Seller
				"seller_tin"		=> $_REQUEST['st'],
				"seller_name"		=> $_REQUEST['sn']
		);
		
		if(empty($act_id)){
			$id		= AddBuyingAct($arr);
			$data	= array('buying_act_id' => $id);
		}
		
		break;
	case 'add_partner_acc':
		$overhead_id 	= $_REQUEST['id'];
		$partner_id 	= GetPartnerID($_REQUEST['bin']);
		
		$arr = array(
					"method"			=> $_REQUEST['pm'],
					"nided"				=> $_REQUEST['pn'],
					"payed"				=> $_REQUEST['p'],
					"needed_date"		=> $_REQUEST['pnd'],
					"type"				=> $_REQUEST['type']
		);
		AddPartnerAcc($overhead_id, $partner_id, $arr);
		
		break;
	case 'check_goods_list':
		$act_id 		= $_REQUEST['id'];
		$check			= ChackGoodsList($act_id);
		if($check){
			$error = 'საქონლის სია ცარიელია!';
		}
		
        break;
	case 'check_partner':
		$partner_id 	= $_REQUEST['id'];
		$check			= ChackPartnerExist($partner_id);
		if($check){
			$error = 'მოახდინეთ პარტნიორის იდენტიფიკაცია!';
		}
		
        break;
    case 'get_local_id':
		$local_id = GetLocalID();
		
		$data = array('local_id' => $local_id);
        
		break;
	case 'get_amount':
		$act_id 		= $_REQUEST['id'];
		$amount 		= GetFullAmount($act_id);
		
		$data = array('amount' => $amount);
		
		break;
	case 'get_seller':
		$tin	 		= $_REQUEST['tn'];
		$name 			= $_REQUEST['nm'];	
		$res 			= GetSeller($tin, $name);			
		if(!$res){
			$error = 'პარტნიორი ვერ მოიძებნა!';
		}else{
			$data = array('tin'		=> $res['tin'],
						  'name'	=> $res['name']);
		}
		
        break;
    case 'clear_db':
		ClearDB();
		
        break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Overhead Out Functions
 * ******************************
 */

function ClearDB()
{
    $req = mysql_query("SELECT `id`
						FROM `overhead_detail`
						WHERE `overhead_id` NOT IN (SELECT `id` FROM `overhead`)");
	
	while( $res = mysql_fetch_assoc($req)){
		mysql_query("DELETE
					 FROM
						`overhead_detail`
					 WHERE
						`id` = $res[id]");
	}
}

function AddBuyingAct($arr)
{
	global $error;
	
	$object_id		= $arr['o_obj'];
	
	$result = mysql_query("INSERT INTO `overhead`
							(`id`, `stream`, `status`, `waybill_number`, `activate_date`, `is_confirmed`, `confirmation_date`) 
						   VALUES
							($arr[lid], 2, $arr[status], '$arr[d_number]', '$arr[activate_date]', 2, '$arr[activate_date]')");
	
	$id				= mysql_insert_id();
	$full_amount	= GetFullAmount($id);
	
	if (!$result) {
		$error = 'Invalid query: ' . mysql_error() . '\n';
	}else{
		//Saller
		$result = mysql_query("UPDATE
					    			`overhead`
							   SET
								    `seller_tin`	= '$arr[seller_tin]',
								    `seller_name`	= '$arr[seller_name]',
								    `full_amount`	= '$full_amount'
							   WHERE
									`id` = $id");
		if (!$result) {
			$error .= 'Invalid query: ' . mysql_error() . '\n';
		}
		
		AddReserve($id, $object_id);
		
		return $id;
	}
}

function AddReserve($overhead_id, $object){
	$req = mysql_query("SELECT  `OD`.`goods_id`,
								`OD`.`quantity`,
								`OD`.`price`,
								`O`.`activate_date`
						FROM `overhead_detail` AS `OD` LEFT JOIN `overhead` AS `O`
						ON `OD`.`overhead_id` = `O`.id
						WHERE `OD`.`overhead_id` = $overhead_id");

	while( $res = mysql_fetch_assoc($req)){

		$price		= $res[price];
		$prod_id	= $res[goods_id];
		$vat		= 0;
		$prop		= GetCompanyProperties();
		$pay		= mysql_fetch_assoc(mysql_query("SELECT	`partners`.`vat_payer` as `vat`
													 FROM	`overhead` LEFT JOIN `partners`
													 	ON	`overhead`.`seller_tin` = `partners`.`rs_id`
													 WHERE	`overhead`.`id` = $overhead_id"));
		
		if ($pay['vat'] == 1 && $prop['payer'] == 1) { //Calculate VAT!
			$vat	= $price - ($price / 1.18);
			$price	= $price / 1.18;
		}
		
		$car = mysql_query("SELECT	`PR`.`id`
							FROM	`production` AS `PR`
							WHERE	`PR`.`id` in (SELECT `production_id` FROM `cartridge_identity`) && `PR`.`actived` = 1 && PR.id = $prod_id");
		
		//check production is cartridge
		if (mysql_num_rows($car) == 0){
			mysql_query("INSERT INTO `reserve`
							(`object_id`, `overhead_id`, `production_id`, `quantity`, `price`, `real_price`, `vat`, `create_date`)
						 VALUES
							($object, $overhead_id, $prod_id, $res[quantity], $price, $res[price], $vat, '$res[activate_date]')");
		}else{
			for ($i = 0; $i < $res[quantity]; $i++) {
				mysql_query("INSERT INTO `reserve`
								(`object_id`, `overhead_id`, `production_id`, `quantity`, `price`, `real_price`, `vat`, `create_date`)
							 VALUES
								($object, $overhead_id, $prod_id, 1, $price, $res[price], $vat, '$res[activate_date]')");
			}
		}
		
		mysql_query("INSERT INTO `overhead_identity`
						(`overhead_id`, `identity_id`, `quantity`, `price`)
					 VALUES
						($overhead_id, 0, $res[quantity], $price)");
		
		$prod = mysql_query("SELECT	`price`
							 FROM	`reserve`
							 WHERE	`production_id` = $prod_id");

		if (mysql_num_rows($prod) != 0){
			$price = mysql_fetch_assoc($prod);
			if($price['price'] != $res){
				$self_price = GetSelfPrice($prod_id);

				mysql_query("UPDATE `reserve`
							 SET	`price` = $self_price
							 WHERE	`production_id` = $prod_id" );

			}
		}
	}
}

function AddPartnerAcc($overhead_id, $partner_id, $arr)
{
	$c_data = date('Y-m-d H:i:s');
	$type	= $arr[type];
	mysql_query("INSERT INTO `partner_accounts`
					(`transfer_type`,`partner_id`, `overhead_id`, `pay_method`, `payed`, `pay_needed`, `pay_date`, `pay_needed_date`)
				 VALUES
					($type, '$partner_id', $overhead_id, $arr[method], $arr[payed], $arr[nided], '$c_data', '$arr[needed_date]')");

	$credit = 0;
	$debit	= 0;

	if($type == 0){
		if($arr[payed] < $arr[nided]){
			$credit = $arr[nided] - $arr[payed];
		}elseif ($arr[payed] > $arr[nided]){
			$debit = $arr[payed] - $arr[nided];
		}
	}else{
		if($arr[payed] < $arr[nided]){
			$debit = $arr[nided] - $arr[payed];
		}elseif ($arr[payed] > $arr[nided]){
			$credit = $arr[payed] - $arr[nided];
		}
	}

	mysql_query("UPDATE `partners`
					SET	`money_credit` = `money_credit` + $credit,
						`money_debit` = `money_debit` + $debit
				 WHERE `id` = $partner_id" );
}

function ChackGoodsList($act_id)
{
	$check = false;
	$req = mysql_query("SELECT `id`
						FROM `overhead_detail`
						WHERE `overhead_id` = $act_id");

	if (mysql_num_rows($req) == 0){
		$check = true;
	}

	return $check;
}

function ChackPartnerExist($partner_id)
{
	$check = false;
	$req = mysql_query("SELECT `id`
						FROM	`partners`
						WHERE	`rs_id` = '$partner_id'");
	
	if (mysql_num_rows($req) == 0){
		$check = true;
	}	
	
	return $check;
}

function GetLocalID()
{
	$result	= mysql_query("SHOW TABLE STATUS LIKE 'overhead'");  
	$row	= mysql_fetch_array($result);
	return $row['Auto_increment'];
}

function GetPartnerID($partner_id)
{
	$res = mysql_fetch_assoc(mysql_query("SELECT `id`
										  FROM	 `partners`
										  WHERE  `rs_id` = '$partner_id'"));
	return $res['id'];
}

function GetCompanyProperties()
{
	$res = mysql_fetch_assoc(mysql_query("SELECT `tin`,
    											 `s_user_id`,
    											 `un_id`,
    											 `name`,
											     `address`,
											     `payer`
									      FROM `company_properties`"));
	return $res;
}

function GetCompanyAccount($act_id)
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `pay_method`,
    											 SUM(`payed`) AS `payed`,
    											 `pay_needed_date`
									      FROM `partner_accounts`
										  WHERE `overhead_id` = '$act_id'
										  GROUP BY `overhead_id`"));
	return $res;
}

function GetSelfPrice($production_id)
{
	$res = mysql_query("SELECT  SUM(`reserve`.`price` * (`reserve`.`quantity` - `reserve`.`sold`)) / SUM(`reserve`.`quantity`  -  `reserve`.`sold`) AS `self_cost`
						FROM `reserve`
						WHERE `reserve`.`production_id` = $production_id
						GROUP BY `reserve`.`production_id`");

	$row = mysql_fetch_assoc($res);
	return $row['self_cost'];
}

function GetFullAmount($act_id)
{
	$res = mysql_fetch_assoc(mysql_query("SELECT SUM(`amount`) AS `full_amount`
										  FROM `overhead_detail`
										  WHERE `overhead_id` = $act_id
										  GROUP BY `overhead_id`"));
	return $res['full_amount'];
}

function GetObject($act_id)
{
	$data = '';
    $req = mysql_query("SELECT `id`, `name`
						FROM `object`
						WHERE `type` != 1 && `type` != 3 && `type` != 5 && `type` != 7"); // <<<<---------------------Type!!!
    
    if(!empty($act_id)){
    	$obj = mysql_fetch_assoc(mysql_query("SELECT `object_id`
											  FROM `reserve`
											  WHERE `overhead_id` = $act_id
											  GROUP BY `overhead_id`"));
    }
	
	while( $res = mysql_fetch_assoc($req)){			
		if($res['id'] == $obj['object_id']){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}				
	}
	
	return $data;
}

function PayMethod($point)
{
	$data = '';
	$req = mysql_query("SELECT `id`, `name`
							FROM `pay_method`");

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}

	return $data;
}

function GetSeller($tin, $name) 
{
	if($tin != ''){
		$res = mysql_query("	SELECT `name` AS `name`,
									   `rs_id` AS `tin`
								FROM `partners`
								WHERE `rs_id` = '$tin'");
	}else{
		$res = mysql_query("	SELECT `name` AS `name`,
									   `rs_id` AS `tin`
								FROM `partners`
								WHERE `name` = '$name'");
	}
	
	if (mysql_num_rows($res) == 0){
		return false;
	}
	$row = mysql_fetch_assoc($res);
	return $row;
}

function GetBuyingAct($act_id) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `id`,
    											 `waybill_number`,
    											 DATE(`activate_date`) AS `activate_date`,
    											 `seller_tin`,
    											 `seller_name`,
    											 `status`,
												 `full_amount`
									      FROM `overhead`
									      WHERE `id` = $act_id"));
	return $res;
}

function GetPage($res = '')
{
	$data  = '
	<!-- jQuery Dialog -->
    <div id="add-edit-goods-form" class="form-dialog" title="საქონელი">
    	<!-- aJax -->
	</div>
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>

	    	<table width="80%" class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="d_number">დოკუმენტის №</label></td>
					<td style="width: 170px;"><label for="operation_data">ოპერაციის თარიღი</label></td>
					<td style="width: 170px;"><label for="object" class="object">საწყობი</label></td>
				</tr>
				<tr>
					<td>
						<input type="text" id="d_number" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['waybill_number'] . '" />
					</td>
					<td>
						<input type="text" id="operation_data" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['activate_date'] . '" />
					</td>
					<td>
						<select id="object" class="idls object">' . GetObject($res['id']) . '</select>
					</td>
				</tr>
			</table>
        </fieldset>
    ';
	
    $data .= GetRelationsSection($res);
    $data .= GetAccountSection($res);
    
    $data .= '
		<fieldset>
	    	<legend>საქონელი</legend>

		    <div class="inner-table">
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" class="overhead_container">
			        	<div id="button_area">
			        		<button id="add_button_goods">დამატება</button><button id="delete_button_goods">წაშლა</button>
			        	</div>
			            <div id="dynamic">';
	$data .= GetTableSection();
	$data .= '
			            </div>
			        </div>
			    </div>
			</div>
		</fieldset>
		<!-- ID -->
		<input type="hidden" id="buying_id" value="' . $res['id'] . '" />
		<input type="hidden" id="local_buying_id"/>
		<input type="hidden" id="status" value="' . $res['status'] . '" />
    </div>    
    ';
    
	return $data;
}

function GetRelationsSection($res = '')
{
	$data .= '        
		<fieldset>
			<legend>გამყიდველი (გამგზავნი)</legend>
		
			<table width="95%" class="dialog-form-table">
				<tr>
					<td style="width: 200px;"><label for="seller_tin">საიდენტ. ნომერი</label></td>
					<td style="width: 300px;"><label for="seller_name">დასახელება / სახელი, გვარი</label></td>
					<td style="width: 350px;"></td>
				</tr>
				<tr>
					<td>
						<input type="text" id="seller_tin" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['seller_tin'] . '" />
					</td>
					<td>
						<div class="seoy-row" id="seller_name_seoy">
							<input type="text" id="seller_name" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" value="' . $res['seller_name'] . '" />
							<button id="seller_name_btn" class="combobox">seller_name</button>
						</div>
					</td>
					<td></td>
				</tr>
			</table>
		</fieldset>
	';
	
	return $data;
}

function GetAccountSection($res = '')
{
	$account = GetCompanyAccount($res['id']);
	$data .= '
		<fieldset>
			<legend>ანგარიშწორება</legend>

			<table width="90%" class="dialog-form-table">
				<tr>
					<td style="width: 200px;"><label for="pay_method">ანგარიშსწორების ფორმა</label></td>
					<td style="width: 150px;"><label for="pay_nided">სულ გადასახდელი</label></td>
					<td style="width: 150px;"><label for="payed">გადახდილი</label></td>
					<td style="width: 300px;"><label for="pay_needed_date">დავალიანების გადახდის თარიღი</label></td>
				</tr>
				<tr>
					<td>
						<select id="pay_method" class="idls">' . PayMethod($account['pay_method']) . '</select>
					</td>
					<td>
						<input type="text" id="pay_nided" class="idle price" disabled="disabled" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $res['full_amount'] . '" />
					</td>
					<td>
						<input type="text" id="payed" class="idle price" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $account['payed'] . '" />
					</td>
					<td>
						<input type="text" id="pay_needed_date" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $account['pay_needed_date'] . '" />
					</td>
				</tr>
			</table>
		</fieldset>
		';

	return $data;
}

function GetTableSection()
{
	$data = '
				<table class="display" id="goods_list">
                    <thead>
                        <tr id="datatable_header">				                        
                            <th>ID</th>
                            <th style="width: 40px">№</th>
                            <th class="min">საქონლის კოდი</th>
                            <th style="width: 296px">საქონლის დასახელება</th>
                            <th style="width: 100px">ზომის<br/>ერთეული</th>
                            <th style="width: 80px">რაოდ.</th>
                            <th style="width: 80px">ერთ.<br/>ფასი</th>
                            <th style="width: 105px">საქონლის<br/>ფასი</th>
                            <th class="check">#</th>
                        </tr>
                    </thead>
                    <thead>
                        <tr class="search_header">				                        
                            <th class="colum_hidden">
                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
                            </th>
                            <th>
                            	<input type="text" name="search_number" value="ფილტრი" class="search_init hidden-input" />
                            </th>
                            <th>
                                <input type="text" name="search_code" value="ფილტრი" class="search_init" />
                            </th>
                            <th>
                                <input type="text" name="search_name" value="ფილტრი" class="search_init" />
                            </th>
                            <th></th>
                            <th></th>
                            <th></th>
                            <th></th>
							<th><input type="checkbox" name="check-all" id="check-all-goods"></th>
                        </tr>
                    </thead>
                </table>';
	
	return $data;
}

?>